2023/12/231896字符
继承模式
1.传统形式 —— 原型链
Grade.prototype.lastName = "wang";
function Grade(){}
var grade = new Grade();
Father.prototype = grade;
function Father(){
this.name = 'hehe';
}
var father = new Father();
Son.prototype = father;
function Son(){}
var son = new Son();
过多的继承了没用的属性
2.借用构造函数
function Person () {
this.name = name;
this.age = age;
this.sex = sex;
}
function Student (name, age, sex, grade) {
Person.call(this, name, age, sex);
this.grade = grade;
}
var student = new Student();
不能继承借用构造函数的原型 每次构造函数都要多走一个函数
3.共享原型(复制)
Father.prototype.lastName = 'deng';
function Father () {
}
function Son () {
}
function inherit(Target, Origin){
Target.prototype = Origin.prototype;
}
inherit(Son, Father);
var son = new Son();
var father = new Father();
不能随便改动自己的原型
4.圣杯模式
function inherit (Target, Origin) {
function F () {};
F.prototype = Origin.prototype;
Target.prototype = new F();
Target.prototype.constuctor = Target; // 防止指向紊乱
Target.prototype.uber = Origin.prototype; // 寻找自己的超类
}
Father.prototype.lastName = 'deng';
function Father(){};
function Son(){};
inherit(Son, Father);
var son = new Son();
var father = new Father();
雅虎封装 inherit 方法
var inherit = (function () {
var F = function () {};
return function (Target, Origin) {
F.prototype = Origin.prototype;
Target.prototype = new F();
Target.prototype.constuctor = Target; // 防止指向紊乱
Target.prototype.uber = Origin.prototype; // 寻找自己的超类
}
}());